package org.cainiao.portal.dao.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.cainiao.portal.dao.mapper.DocumentMapper;
import org.cainiao.portal.entity.document.Document;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <br />
 * <p>
 * Author: Cai Niao(wdhlzd@163.com)<br />
 */
@Service
public class DocumentMapperService
    extends ServiceImpl<DocumentMapper, Document> implements IService<Document> {

    public List<Document> findDocumentByKnowledgePointIdAndPublished(@Param("knowledgePointId") long knowledgePointId,
                                                                     @Param("published") boolean published) {
        return getBaseMapper().findDocumentByKnowledgePointIdAndPublished(knowledgePointId, published);
    }

    public boolean existsByOwnerOpenIdAndParentIdAndExternalId(String ownerOpenId,
                                                               Long parentId, String externalId) {
        LambdaQueryChainWrapper<Document> lambdaQueryChainWrapper = lambdaQuery()
            .eq(Document::getOwnerOpenId, ownerOpenId).eq(Document::getExternalId, externalId);
        setParentIdCondition(lambdaQueryChainWrapper, parentId);
        return lambdaQueryChainWrapper.exists();
    }

    public List<Document> findByOwnerOpenIdAndParentId(String ownerOpenId, Long parentId) {
        LambdaQueryChainWrapper<Document> lambdaQueryChainWrapper = lambdaQuery()
            .eq(Document::getOwnerOpenId, ownerOpenId);
        setParentIdCondition(lambdaQueryChainWrapper, parentId);
        return lambdaQueryChainWrapper.orderByAsc(Document::getOrder).list();
    }

    private static void setParentIdCondition(LambdaQueryChainWrapper<Document> lambdaQueryChainWrapper, Long parentId) {
        if (parentId == null) {
            lambdaQueryChainWrapper.isNull(Document::getParentId);
        } else {
            lambdaQueryChainWrapper.eq(Document::getParentId, parentId);
        }
    }
}
